﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;

namespace JDML.MappingClass
{
    public class FieldMapping
    {
        private bool isMapping = true;
        private bool dbPrimaryKey = false;
        private bool dbAutoGenerate = false;
        public string FieldName { get { return FieldInfo.Name; } }
        public Type FieldType { get; set; }
        public string DBFieldName { get; set; }
        public DbType DbFieldType { get; set; }
        public bool DBPrimaryKey 
        {
            get
            {
                return dbPrimaryKey;
            }
            set
            {
                dbPrimaryKey = value;
                dbAutoGenerate = dbPrimaryKey ? true : false;
            }
        }
        public bool DBAutoGenerate 
        {
            get 
            { 
                return dbAutoGenerate;
            }
            set 
            {
                if (value && (!dbPrimaryKey))
                {
                    throw new Exception("只有Primary Key 才能表示为Identity自动生成。");
                }
                dbAutoGenerate = value; 
            } 
        }
        public bool IsMapping { get { return isMapping; } set { isMapping = value; } }
        public MemberInfo FieldInfo { get; set; }
        public Object GetValue(Object o)
        {
            object value = null;
            if (FieldInfo is PropertyInfo)
            {

                value = (FieldInfo as PropertyInfo).GetValue(o, null);
            }
            else
            {
                value = (FieldInfo as FieldInfo).GetValue(o);
            }
            return value;
        }
        public bool SetValue(Object o, Object value)
        {
            if (value != null)
            {
                Object newvalue = Convert.ChangeType(value, FieldType);
                if (FieldInfo is PropertyInfo)
                {
                    (FieldInfo as PropertyInfo).SetValue(o, newvalue, null);
                }
                else
                {
                    (FieldInfo as FieldInfo).SetValue(o, newvalue);
                }
                return true;
            }
            return false;
        }
    }
}
